import "./index.scss"
import {useNavigate} from "react-router-dom";
import LivingIcon from "@src/components/LivingIcon";
import {socketCreate} from "@src/store/socket"
import {useEffect, useState} from "react";
import {useRequest} from "ahooks";
import {CurrentSong, getChatroomList, RoomType} from "@src/services/chatRoom"
import toast from 'react-hot-toast';

export interface Member {
    avatar: string;
    name: string;
    email: string | null;
    isVisitor: boolean | undefined;
}

interface Group {
    groupId: string;
    members: Member[];
    memberCount: number;
    messageCount: number;
}

export interface states {
    "groupId": string,
    "isPlaying": boolean,
    "progress": number,
    song: CurrentSong
}

export interface chatRoomListDataType extends RoomType {
    users?: Member[];
    states?: states
}

const getChatRoomListDataTypeData = (data: RoomType[], groups: Group[], states: states[]) => {
    const newData = data.map(chatRoom => {
        const matchedGroup = groups.find(group => group?.groupId === chatRoom.roomID.toString());
        const matchedStates = states.find(state => state?.groupId === chatRoom.roomID.toString());
        const isPlaying = (matchedStates?.isPlaying != undefined) ? (matchedGroup?.members.length == 0 ? false : matchedStates.isPlaying) : false
        const newStates: states = {
            groupId: chatRoom.roomID.toString(),
            isPlaying: isPlaying,
            progress: matchedStates?.progress ? matchedStates.progress : 0,
            song: matchedStates?.song.id ? matchedStates.song : chatRoom.currentSong
        }
        return {...chatRoom, users: matchedGroup?.members, states: newStates};
    })
    sessionStorage.setItem("chatRoomListData", JSON.stringify(newData));
    return newData;
}


export default function ChatRoom() {
    //获取聊天室基本信息
    const chatRoomListAPi = useRequest(getChatroomList, {manual: true})
    //存放聊天室 基本信息
    const [chatRoomListData, setChatRoomListData] = useState<chatRoomListDataType[]>();
    //存放 聊天室用户列表
    const [groups, setGroups] = useState<Group[]>([]);
    //存放 聊天室状态
    const [states, setStates] = useState<states[]>([]);
    // 未进入聊天室的用户
    const [leisureMember, setLeisureMember] = useState<Member[]>([]);
    const {socket} = socketCreate();
    const navigate = useNavigate();
    //进入聊天室
    const goToChatRoomDetailed = (state: chatRoomListDataType) => {
        if (state.users && state.users.length >= state.maxUsersLength) {
            toast.success("这个聊天室已经挤不进去了呢~", {icon: "😫"});
        } else {
            navigate("chatRoomDetailed", {state: state});
        }
    }
    //获取聊天室列表
    useEffect(() => {
        if (chatRoomListData === undefined) {
            const chatRoomListData = sessionStorage.getItem("chatRoomListData");
            if (chatRoomListData) {
                setChatRoomListData(JSON.parse(chatRoomListData));
            } else {
                chatRoomListAPi.runAsync().then((data) => {
                    setChatRoomListData(getChatRoomListDataTypeData(data.data, groups, states))
                })
            }

        }
    }, []);
    useEffect(() => {
        //获取房间 人数
        socket.on('group:all_groups', (data) => {
            setGroups(data.groups)
            socket.emit('group:get_online_users_not_in_groups');
            setChatRoomListData((chatRoomListData) => {
                if (chatRoomListData) {
                    const newChatRoomListData = getChatRoomListDataTypeData(chatRoomListData, data.groups, states)
                    setStates((item) => {
                        return item.map((item2) => {
                            const newChatRoom = newChatRoomListData.find(room => room.roomID.toString() === item2.groupId.toString());
                            if (newChatRoom) {
                                item2.isPlaying = newChatRoom.isPlaying
                            }
                            return item2;
                        })
                    })
                }
                return chatRoomListData
            })
        })
        //获取状态
        socket.on('group:all_playback_states', (data) => {
            setStates(data.states)
        });
        //获取未进入聊天室 用户列表
        socket.on("group:online_users_not_in_groups", (data) => {
            setLeisureMember(() => {
                const arr: Member[] = data.users
                arr.filter((item, index) => arr.indexOf(item) === index)
                return arr.filter((item, index) => arr.indexOf(item) === index)
            })
        })
        //获取房间 人数
        socket.emit('group:get_all_groups');
        //获取房间 状态
        socket.emit('group:get_all_playback_states');

        return () => {
            socket.off('group:all_groups')
            socket.off('group:all_playback_states')
            socket.off('group:online_users_not_in_groups')
        };
    }, [socket])

    //监听 播放时状态
    useEffect(() => {
        if (chatRoomListData) {
            const newChatRoomListData = getChatRoomListDataTypeData(chatRoomListData, groups, states)
            setChatRoomListData(newChatRoomListData)
        }
    }, [states]);


    return <div className="ChatRoomContainer">

        <div className="leisure-member">
            <div className="centered">
                閑
            </div>
            <div className="user-list">
                <ul>
                    {leisureMember?.map((user) =>
                        <li key={user.avatar}>
                            <img className="userHead" src={user.avatar} alt=""/>
                            <p className="text-overflow-1">{user.name}</p>
                        </li>
                    )}
                </ul>
            </div>
        </div>
        <div className="ChatRoomContainer-main">
            <ul className="chat-room">
                {chatRoomListData && chatRoomListData.map((chatRoom) =>
                    <li key={chatRoom.title} onClick={() => goToChatRoomDetailed(chatRoom)}>
                        <div className="cover"><img alt="" src={chatRoom.img}/></div>
                        <div className="content">
                            <p>{chatRoom.title}</p>
                            <p>{chatRoom.intro}</p>
                            <div className="text-overflow-1 name">{chatRoom.states?.isPlaying &&
                                <LivingIcon/>} {chatRoom.states?.song.name}</div>
                            <div className="user-list">
                                <ul>
                                    {chatRoom.users?.map((user) =>
                                        <li key={user.avatar}>
                                            <img className="userHead" src={user.avatar} alt=""/>
                                        </li>
                                    )}
                                </ul>
                                <p>{chatRoom.users?.length ?? 0}/{chatRoom.maxUsersLength}</p>
                            </div>
                        </div>
                    </li>
                )}
            </ul>
        </div>

    </div>
}